package lu.med.praxiswahl.wahlumed.dao.beans;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import lu.med.praxiswahl.wahlumed.dao.beans.daointerface.BefundeDAOInt;
import lu.med.praxiswahl.wahlumed.model.beans.BefundeTBL;
import lu.med.praxiswahl.wahlumed.model.beans.CustomerTBL;

/**
 * Session Bean implementation class BefundeDAO
 * @author Patrick kendzo
 * Email: pkendzo@msn.com
 */

@Stateless
public class BefundeDAO implements BefundeDAOInt {
	
	@PersistenceContext(unitName = "gynaekomedic-ejbPU")
	private EntityManager	em	= null;

    /**
     * Default constructor. 
     */
    public BefundeDAO() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see BefundeDAOInt#update(BefundeTBL)
     */
    public void update(BefundeTBL todo) {

		em.merge(todo);
		em.flush();
    }

	/**
     * @see BefundeDAOInt#retrieveBefundeItemByID(Long)
     */
    public BefundeTBL retrieveBefundeItemByID(Long id) {

    	return em.find(BefundeTBL.class, id);
    }

	/**
     * @see BefundeDAOInt#retrieveBefundeItemsByCustomer(String)
     */
    @SuppressWarnings("unchecked")
    public List<BefundeTBL> retrieveBefundeItemsByCustomer(String matricule) {
    	try
		{
			return (List<BefundeTBL>) em.createQuery(
					"select a from BefundeTBL a where a.customer = '"
							+ matricule + "' order by a.datum desc").getResultList();
		}
		catch (Exception e)
		{
			throw new RuntimeException(
					"Could not retrieve Zytoloy item for this Customer", e);
		}
    }

	/**
     * @see BefundeDAOInt#delete(Long)
     */
    public void delete(Long todo) {
    	
    	BefundeTBL item = this.retrieveBefundeItemByID(todo);

		CustomerTBL cust = item.getCustomer();

		cust.getBefunde().remove(item);

		em.remove(item);
		em.flush();
		
    }

	/**
     * @see BefundeDAOInt#persist(BefundeTBL)
     */
    public void persist(BefundeTBL todo) {
        
    	em.persist(todo);
		em.flush();
    }

    public Long findDatabaseSubPrimaryKeyIndex() {
        try
		{
			
			Long result = (Long)em
					.createQuery(
							"select max(befunde_nummer) from BefundeTBL b ").getSingleResult();
			
			return result.longValue();
		}
		catch (Exception e)
		{
			/*throw new RuntimeException("OrdonanceTBL is empty",
					e);*/
			return -1l;
		}
    }

}
